import axios from 'axios';
import store from '@/store';
import md5 from 'md5'; // 密码加密
import bcrypt from 'bcryptjs';
const password = 'your-password';
const hashed = md5(password);
const salt = bcrypt.genSaltSync(10);
const bcryptHash = bcrypt.hashSync(password, salt);
bcrypt.hash(password, 10, function(err, hash) {
    if (err) {
        console.log(err);
    } else {
        // hash 就是加密后的密码，可存储到数据库等
        console.log(hash);
    }
});
const API_URL = 'http://localhost:8080/library'; // 后端API地址

class AdminService {
    // 获取所有管理员
    getAllAdmins() {
        return axios.get(`${API_URL}/admins?action=list`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 根据ID获取管理员
    getAdminById(id) {
        return axios.get(`${API_URL}/admins?action=get&id=${id}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 添加管理员
    addAdmin(admin) {
        // 对密码进行MD5加密
        const adminData = {
            ...admin,
            password: md5(admin.password)
        };

        return axios.post(`${API_URL}/admins?action=add`, adminData, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 更新管理员
    updateAdmin(admin) {
        // 如果有新密码则加密
        const adminData = admin.password ? {
            ...admin,
            password: md5(admin.password)
        } : admin;

        return axios.post(`${API_URL}/admins?action=update`, adminData, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 删除管理员
    deleteAdmin(id) {
        return axios.delete(`${API_URL}/admins?id=${id}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 搜索管理员
    searchAdmins(keyword) {
        return axios.get(`${API_URL}/admins?action=search&keyword=${keyword}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 获取认证头
    getAuthHeader() {
        const token = store.state.auth.token;
        if (token) {
            return { 'Authorization': 'Bearer ' + token };
        } else {
            return {};
        }
    }

    // 模拟数据方法 - 在实际连接API后可移除
    static mockData() {
        return [
            {id: 1, username: 'admin', name: '系统管理员', role: 'admin'},
            {id: 2, username: 'manager1', name: '图书管理员1', role: 'manager'},
            {id: 3, username: 'manager2', name: '图书管理员2', role: 'manager'},
            {id: 4, username: 'auditor1', name: '审计员', role: 'auditor'},
            {id: 5, username: 'report1', name: '报表管理员', role: 'reporter'}
        ];
    }
}

// 导出单例实例
export default new AdminService();